package com.launcher.wkang.activity;


import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.os.RemoteException;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.launcher.wkang.App;
import com.launcher.wkang.R;
import com.launcher.wkang.adapter.LauncherAdapter;
import com.launcher.wkang.bean.CouListBean;
import com.launcher.wkang.bean.CourseBean;
import com.launcher.wkang.bean.TimeBean;
import com.launcher.wkang.bean.WeatherBean;
import com.launcher.wkang.fragment.Fragment1;
import com.launcher.wkang.fragment.Fragment2;
import com.launcher.wkang.fragment.Fragment3;
import com.launcher.wkang.fragment.Fragment4;
import com.launcher.wkang.fragment.Fragment5;
import com.launcher.wkang.receive.BatteryReceiver;
import com.launcher.wkang.service.ContactService;
import com.launcher.wkang.util.NetUtils;
import com.launcher.wkang.util.PhoneUtil;
import com.launcher.wkang.util.Url;
import com.launcher.wkang.view.LauncherViewPager;


import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static cn.jpush.android.api.JPushInterface.getRegistrationID;

//import io.rong.imlib.RongIMClient;

public class LauncherActivity  extends FragmentActivity implements View.OnFocusChangeListener, ViewPager.OnPageChangeListener {
    private LauncherViewPager viewPager;
    private LauncherAdapter launcherAdapter;
    private List<Fragment> fragmentList;
    private LinearLayout divisionLayout;
    private float startX;
    private float endX;
    private Fragment1 fragment1;
    private Fragment2 fragment2;
    private Fragment3 fragment3;
    private Fragment4 fragment4;
    private Fragment5 fragment5;
    private BatteryReceiver receiver;

    public CouListBean couListBean;
    private String hintText;
    private String Token= "irDSkkkw0S4lkfw8aEGCD7gSXwQ//xQ5RHAXlo6Ch3C16a1j0YsnNict5XN0O99HweADD435yNo=";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launcher);
        initView();
        initData();
        initBattery();

    }
    private void initView(){
        viewPager=findViewById(R.id.view_pager);
//        viewPager.setOffscreenPageLimit(5);
        divisionLayout=findViewById(R.id.division_layout);


    }
    private void initData(){
        fragmentList=new ArrayList<Fragment>();
        fragment1=new  Fragment1();

        fragmentList.add(fragment1);
        fragment2=new Fragment2();

        fragmentList.add(fragment2);
        fragment3=new Fragment3();
        fragmentList.add(fragment3);

        fragment4=new Fragment4();
        fragmentList.add(fragment4);

        fragment5=new Fragment5();
        fragmentList.add(fragment5);

        launcherAdapter=new LauncherAdapter(getSupportFragmentManager(),fragmentList);
        viewPager.setAdapter(launcherAdapter);
        viewPager.setCurrentItem(0);
        viewPager.setOnPageChangeListener(this);

        PhoneUtil.setStatusBarFullTransparent(this);
//        Intent intent=new Intent(this,ContactService.class);
//        startService(intent);
//        String registerId=getRegistrationID(this);
//        Intent intent1=new Intent(this,ProhibitActivity.class);
//        startActivity(intent1);
    }

    @Override
    protected void onResume() {
        super.onResume();
        App.getINstance().setsetWaveformMode(2,1);
        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                App.getINstance().setsetWaveformMode(5,1);
            }
        },150);

    }



    @Override
    public void onFocusChange(View v, boolean hasFocus) {

    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {
        for (int j=0;j<divisionLayout.getChildCount();j++){
            ImageView imageView=(ImageView) divisionLayout.getChildAt(j);
            if (i==j){
                imageView.setImageResource(R.mipmap.selected);
            }else {
                imageView.setImageResource(R.mipmap.unselected);
            }
        }

    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }


    public void setCurrentItem(int position){
        viewPager.setCurrentItem(position);
    }
    public void setTimeAndWeather(){
        fragment1.setTimeAndWeather();
    }
    private void initBattery(){
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
//        IntentFilter prohibitFilter = new IntentFilter("ProhibitReceiver");
        receiver = new BatteryReceiver();
//        prohibitReceiver=new ProhibitReceiver();
//        registerReceiver(prohibitReceiver,prohibitFilter);
        registerReceiver(receiver, filter);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁广播
        unregisterReceiver(receiver);
    }



    /**
     * 课程表禁用
     */
    private boolean courseDisabled(){


        if (couListBean!=null){
            ArrayList<TimeBean> dateList=couListBean.getDateList();
            if (dateList!=null&&dateList.size()>0){
                boolean isIntime=false;
                for (int j=0;j<dateList.size();j++){
                    TimeBean timeBean=dateList.get(j);
                    String startTime=timeBean.getStartTime();
                    String format = "HH:mm";

                    isIntime=   isEffectiveDate(startTime,null);
                    if (isIntime) {
                        Calendar cal = Calendar.getInstance();
                        int week_index = cal.get(Calendar.DAY_OF_WEEK)-1 ;
                        if (week_index == 0) {
                            week_index = 7;
                        }
                        ArrayList<ArrayList<CourseBean>> courseList = couListBean.getList();
                        if (courseList != null) {
                            ArrayList<CourseBean> courseBeans = courseList.get(week_index-1);
                            if (courseBeans!=null) {
                                CourseBean courseBean = courseBeans.get(j);
                                if (courseBean!=null){
                                    String courseName=courseBean.getCourseName();
                                    if (!TextUtils.isEmpty(courseName)){
                                        Log.d("courseDisabled","courseDisabled is true");
                                        return true;
                                    }
                                }
                            }
                        }


                    }



                }
            }

        }
        Log.d("courseDisabled","courseDisabled is false");
        return false;

    }

    /**
     * 时间段禁用
     * @return
     */
    private boolean slotDisable() {
        SharedPreferences sharedPreferences = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
        int disableClass = sharedPreferences.getInt("disableClass", 0);
        String amstarttime = sharedPreferences.getString("amstarttime", null);
        String amendtime = sharedPreferences.getString("amendtime", null);

        String pmstarttime = sharedPreferences.getString("pmstarttime", null);
        String pmendtime = sharedPreferences.getString("pmendtime", null);


        String gnstarttime = sharedPreferences.getString("gnstarttime", null);
        String gnendtime = sharedPreferences.getString("gnendtime", null);

        String repeat = sharedPreferences.getString("repeat", null);
        Calendar cal = Calendar.getInstance();
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week_index == 0) {
            week_index = 7;
        }

        if (null!=repeat) {
            String[] itemStrs = repeat.split(",");
            if (itemStrs != null && itemStrs.length > 0)
            {
                for (int j = 0; j < itemStrs.length; j++) {
                    try {

                        int repeatItem = Integer.valueOf(itemStrs[j]);
                        if (repeatItem == week_index) {
                            boolean isInAmTime = isEffectiveDate(amstarttime, amendtime);
                            boolean isInPmtime = isEffectiveDate(pmstarttime, pmendtime);
                            boolean isInGnTime = isEffectiveDate(gnstarttime, gnendtime);
                            return isInAmTime || isInPmtime || isInGnTime;
                        }
                    } catch (NumberFormatException e) {

                    }
                }
        }
        }
        return false;

    }
    private boolean phoneDisable(){

        SharedPreferences sharedPreferences = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
        int disableClass = sharedPreferences.getInt("disableClass", 0);
        String lostStatus=sharedPreferences.getString("lostStatus",null);
        String electricityStatus=sharedPreferences.getString("electricityStatus",null);
        int current = sharedPreferences.getInt("current",-1);// 获得当前电量
        int total = sharedPreferences.getInt("total",-1);// 获得总电量
        if (disableClass==1){
            if (courseDisabled()){
                hintText="上课时间请专心听讲";
                App.getINstance().isAnswer=false;
                return true;
            }
        }
        if (disableClass==2){
            if (slotDisable()){
                hintText="上课时间请专心听讲";
                App.getINstance().isAnswer=false;
                return true;
            }
        }
//        如果之前两个条件不成立说明上课禁用功能不成立
        App.getINstance().isAnswer=true;
        if ("1".equalsIgnoreCase(lostStatus)){
            hintText="不是自己手机请归还失主噢";
            return true;
        }
        if ("1".equalsIgnoreCase(electricityStatus)){
            float present=(float) current/(float) total;
            if (current*10<total||current*10==total) {
                hintText = "手机电量低";
                return true;
            }
        }
        return false;
    }

    /**
     * 判断当前时间是否在[startTime, endTime]区间，注意时间格式要一致
     *
     * @param
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     * @author jqlin
     */
    public static boolean isEffectiveDate(String  startTime, String endTime) {

        String format = "HH:mm";
        Calendar nawDate = Calendar.getInstance();
        try {
            Date startTimeDate = new SimpleDateFormat(format).parse(startTime);
            int startHour=startTimeDate.getHours();
            int startMinute=startTimeDate.getMinutes();
            Log.d("LauncherActivity","startHour="+startHour+"#####startMinute="+startMinute);
            Calendar begin = Calendar.getInstance();
            begin.set(Calendar.HOUR_OF_DAY,startHour);
            begin.set(Calendar.MINUTE,startMinute+1);
            Calendar end = Calendar.getInstance();
            if (!TextUtils.isEmpty(endTime)) {
                Date endTimeDate = new SimpleDateFormat(format).parse(endTime);
                int endHour=endTimeDate.getHours();
                int endMinute=endTimeDate.getMinutes();
                end.set(Calendar.HOUR_OF_DAY,endHour);
                end.set(Calendar.MINUTE,endMinute+1);
            }else {
                end.set(Calendar.HOUR_OF_DAY,startHour);
                end.set(Calendar.MINUTE,startMinute+1);
                end.add(Calendar.MINUTE, 45);
                int hour=end.get(Calendar.HOUR_OF_DAY);
                int minute=end.get(Calendar.MINUTE);
                Log.d("LauncherActivity","hour="+hour+"#####minute="+minute);

            }
//        end.add(Calendar.MINUTE, 45);
            boolean isAfter=nawDate.after(begin);
            boolean isBefore=nawDate.before(end);
            if (isAfter && isBefore) {
                return true;
            } else {
                return false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }

    public void doProhibit(){
        if (phoneDisable()){
            if(!isMainActivityTop()) {
                goHome();
            }
            App.getINstance().isProhibit=true;
            int currentItem=viewPager.getCurrentItem();
            if (currentItem!=0) {
                setCurrentItem(0);
            }
            fragment1.doProhibit(hintText);
        }else {
            App.getINstance().isProhibit=false;
            fragment1.doProhibit(hintText);
        }
    }

    private void goHome(){
        Intent intent = new Intent();
// 为Intent设置Action、Category属性
        intent.setAction(Intent.ACTION_MAIN);// "android.intent.action.MAIN"
        intent.addCategory(Intent.CATEGORY_HOME); //"android.intent.category.HOME"
        startActivity(intent);
    }

    /**
          *
          * 判断mainactivity是否处于栈顶
          * @return  true在栈顶false不在栈顶
          */
    private boolean isMainActivityTop(){
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        return name.equals(LauncherActivity.class.getName());
    }










}
